<script setup>
	import {
		onMounted,
		ref
	} from 'vue';
	import {
		Plus,
		Search
	} from "@element-plus/icons-vue";
	import {
		cancelOrder,
		getOrderDetailPage,
		refundOrder,
		searchOrder
	} from '@/apis/order.js';
	import {
		formatTime
	} from "@/utils/time_common.js";

	const input = ref('');
	const orderStatus = ref('');
	const orderTime = ref([]);
	const beginTime = ref('');
	const endTime = ref('');
	const defaultTime = [
		new Date(2000, 1, 1, 0, 0, 0),
		new Date(2000, 1, 1, 23, 59, 59),
	]
	const counts = ref(0);
	const current = ref(1);
	const size = ref(10);
	const tableData = ref([]);
	const drawer = ref(false);
	const diaForm = ref({});
	const total = ref(0);


	const init = async () => {
		await getOrderDetailPage({
			current: current.value,
			size: size.value
		}).then((res) => {
			console.log(res)
			if (res.data.code === 1) {
				tableData.value = res.data.data.records || [];
				total.value = res.data.data.total;
			}
		}).catch((err) => {
			console.error('请求出错了：' + err);
		})
	};

	const currentChange = (val) => {
		current.value = val;
		findOrder();
	};

	const getOrderType = (s) => {
		let str = '';
		// 订单状态，1表示待支付，2表示已支付，3表示已发货，4表示已完成，5表示已取消，
		switch (s) {
			case 1:
				str = '待付款';
				break;
			case 2:
				str = '已支付';
				break;
			case 3:
				str = '已发货';
				break;
			case 4:
				str = '已完成';
				break;
			case 5:
				str = '已取消'
				break
			default:
				str = '订单状态异常'
		}
		return str;
	};


	function formatProcessingTime(row) {
		return formatTime(row.createTime)
	}

	const findOrder = async () => {
		console.log(orderTime)
		console.log(orderTime.value[0]);
		console.log(orderTime.value[1]);
		console.log(typeof(orderTime.value[1]));

		let params = {
			id: input.value,
			status: orderStatus.value,
			beginTime: orderTime.value[0],
			endTime: orderTime.value[1],
			current: current.value,
			size: size.value,
		};
		await searchOrder(params).then((res) => {
			if (res.data.code === 1) {
				counts.value = res.data.data.total;
				tableData.value = res.data.data.records;
			} else {
				console.error(res.data.msg || '操作失败');
			}
		}).catch((err) => {
			console.error('请求出错了：' + err);
		});
	};

	const goDetail = (row) => {
		console.log("打开弹窗")
		console.log(row)
		drawer.value = true;
		diaForm.value = {
			...row
		};
		console.log("打开")
		console.log(diaForm.value)
	};

	const cancelOrDeliveryOrComplete = (status, id) => {
		// status 1 取消订单 2 退款订单
		if (status === 1) {
			ElMessageBox.confirm('确认取消该订单?', '取消订单', {
				'confirmButtonText': '确定',
				'cancelButtonText': '取消',
				'type': 'warning',
			}).then(() => {
				cancelOrder(id).then((res) => {
					console.log(res);
					if (res.data.code === 1) {
						console.log('订单已取消');
						ElMessage.success('订单已取消');
						init();
					} else {
						console.error(res.data.data.msg || '操作失败');
					}
				}).catch((err) => {
					console.error('请求出错了：' + err);
				});


			});
		} else {
			ElMessageBox.confirm('确认对该订单执行退款?', '退款', {
				'confirmButtonText': '确定',
				'cancelButtonText': '取消',
				'type': 'warning',
			}).then(() => {
				refundOrder(id).then((res) => {
					console.log(res);
					if (res.data.code === 1) {
						console.log('订单已退款');
						ElMessage.success('订单已退款');
						init();
					} else {
						console.error(res.data.data.msg || '操作失败');
					}
				}).catch((err) => {
					console.error('请求出错了：' + err);
				});

			});
		}

	};

	const handleClose = () => {
		drawer.value = false;
	};

	const handleSizeChange = (val) => {
		size.value = val;
		init();
	};

	const handleCurrentChange = (val) => {
		current.value = val;
		init();
	};

	onMounted(() => {
		init();
	});
</script>

<template>
	<div id="order-app" class="dashboard-container">
		<div class="container">
			<!-- 搜索项 -->
			<div class="tableBar">
				<el-form ref="editUser" :inline="true" :model="formData" :rules="rules" label-position="left"
					label-width="92px">
					<el-form-item label="订单号：" label-width="84px" prop="title">
						<el-input v-model="input" placeholder="请输入订单号" style="width: 220px">
						</el-input>
					</el-form-item>
					<!--          订单状态，1表示待支付，2表示已支付，3表示已发货，4表示已完成,5表示已取消-->
					<el-form-item label="订单状态：" label-width="84px" prop="title">
						<el-select v-model="orderStatus" placeholder="请选择" style="width: 220px">
							<el-option label="全部" value=""></el-option>
							<el-option label="待付款" value="1"></el-option>
							<el-option label="已支付" value="2"></el-option>
							<el-option label="已发货" value="3"></el-option>
							<el-option label="已完成" value="4"></el-option>
							<el-option label="已取消" value="5"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="下单时间：" label-width="84px" prop="title">
						<el-date-picker v-model="orderTime" :default-time="defaultTime" clearable type="datetimerange"
							range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
					</el-form-item>
					<el-form-item label-width="0">
						<el-button :icon="Search" type="primary" @click="findOrder">查询</el-button>
					</el-form-item>
				</el-form>
			</div>
			<el-table :data="tableData" class="tableBox">
				<el-table-column label="订单号" prop="id"></el-table-column>
				<el-table-column label="商品标题" prop="productName"></el-table-column>
				<el-table-column label="下单时间" prop="createTime" :formatter="formatProcessingTime"></el-table-column>
				<el-table-column label="金额" prop="totalPrice"></el-table-column>
				<el-table-column label="订单状态" prop="status">
					<template #default="scope">
						<span>{{ getOrderType(scope.row.status) }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center">
					<template #default="scope">
						<!--            订单状态，1表示待支付，2表示已支付，3表示已发货，4表示已完成，5表示已取消，，-->
						<el-button class="blueBug" type="text" @click="goDetail(scope.row)">查看</el-button>
						<el-button v-if="scope.row.status >= 2 && scope.row.status !=5" class="blueBug" type="text"
							@click="cancelOrDeliveryOrComplete(2, scope.row.id)">退款
						</el-button>
						<el-button v-if="scope.row.status !== 5" class="blueBug" type="text"
							@click="cancelOrDeliveryOrComplete(1, scope.row.id)">取消订单
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-pagination v-model:current-page="current" :total=total background class="pageList"
				layout="prev, pager, next" @current-change="currentChange" />
		</div>

		<!-- 查看弹框部分 -->
		<el-drawer v-model="drawer" title="订单详情" size="30%">

			<el-descriptions :column="2" label-style="{ width: '80px' }">
				<el-descriptions-item label="订单号" :span="2">
					{{ diaForm.id }}
				</el-descriptions-item>
				<el-descriptions-item label="商品标题" :span="2">
					{{ diaForm.productName }}
				</el-descriptions-item>
				<el-descriptions-item label="出售用户" :span="2">
					{{ diaForm.sellerName }}
				</el-descriptions-item>
				<el-descriptions-item label="购买用户" :span="2">
					{{ diaForm.buyerName }}
				</el-descriptions-item>
				<el-descriptions-item label="下单时间" :span="2">
					{{ diaForm.createTime }}
				</el-descriptions-item>
				<el-descriptions-item label="下单时间" :span="2">
					{{ diaForm.createTime }}
				</el-descriptions-item>

				<el-descriptions-item label="支付金额" :span="2">
					{{ diaForm.totalPrice }}
				</el-descriptions-item>
				<el-descriptions-item label="订单状态" :span="2">
					{{ getOrderType(diaForm.status) }}
				</el-descriptions-item>
				<el-descriptions-item label="物流单号" :span="2">
					{{ diaForm.logisticsNum }}
				</el-descriptions-item>
				<el-descriptions-item label="备注" :span="2">
					{{ diaForm.remarks }}
				</el-descriptions-item>
			</el-descriptions>
		</el-drawer>
	</div>
</template>
<style scoped>
@import "@/styles/page.css";
@import "@/styles/page.css";
.block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.el-button {
  padding: 5px 11px;
  border-radius: calc(var(--el-border-radius-base) - 1px);
}
.el-descriptions {
  margin-bottom: 20px;
}
</style>